from fastapi import APIRouter, Depends, HTTPException, Request, File, UploadFile
from typing import Optional
import os
import uuid
import aiofiles
from auth import get_current_active_user, User

router = APIRouter(prefix="/api", tags=["files"])

# 文件上传
@router.post("/upload")
async def upload_file(request: Request, file: UploadFile = File(...)):
    """上传媒体文件"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        raise HTTPException(status_code=401, detail="未授权访问")

    file_extension = file.filename.split(".")[-1]
    unique_filename = f"{uuid.uuid4()}.{file_extension}"
    file_path = f"static/media/{unique_filename}"

    # 确保目录存在
    os.makedirs(os.path.dirname(file_path), exist_ok=True)

    async with aiofiles.open(file_path, 'wb') as f:
        content = await file.read()
        await f.write(content)

    return {"filename": unique_filename, "path": file_path}
